package com.davidlife.services.objserialization;

import java.io.*;

/**
 * 基于Java内置的序列化方式
 * 不需要引入第三方包，使用简单，在对效率要求不敏感的场景下，也是一个不错的选择
 */
public class JavaSerialization {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String str = "abc";
        byte[] bytes = serializeObj(str);
        System.out.println(bytes);
        String str2 = (String) deserializeObj(bytes);
        System.out.println(str2);
    }

    //对象序列化
    public static byte[] serializeObj(Object o) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(o);
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    //对象反序列化
    public static Object deserializeObj(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bis);
        Object o = ois.readObject();
        return o;
    }
}
